package org.xjc.autoconfiguration;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.xjc.config.securitycomponent.*;
import org.xjc.entity.SecurityUserEntity;
import org.xjc.service.SecurityRoleService;
import org.xjc.service.SecurityUserService;

/**
 * @Author : XJC
 * @Description :自定义的AutoConfiguration
 * @create : 2022/9/30 10:57
 */
@Configuration
@Order(0)
@EnableConfigurationProperties(JwtProperties.class)
public class XPackAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(CustomSecurityMetadataSourceFilter.class)
    public FilterInvocationSecurityMetadataSource customSecurityMetadataSourceFilter() {
        return new CustomSecurityMetadataSourceFilter();
    }

    @Bean
    @ConditionalOnMissingBean(CustomUrlDecisionManager.class)
    public AccessDecisionManager customUrlDecisionManager() {
        return new CustomUrlDecisionManager();
    }

    @Bean
    @ConditionalOnMissingBean(JwtTokenUtil.class)
    public JwtTokenUtil jwtTokenUtil() {
        return new JwtTokenUtil();
    }

    @Bean
    @ConditionalOnMissingBean(PasswordEncoder.class)
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService(SecurityUserService userService, SecurityRoleService roleService){
        return username -> {
            SecurityUserEntity securityUserEntity =userService.getUserByUserName(username);
            if (null!= securityUserEntity){
                //设置角色进行权限控制
                securityUserEntity.setRoles(roleService.queryUserRolesByUserId(securityUserEntity.getId()));
                return securityUserEntity;
            }
            throw new UsernameNotFoundException("用户名或密码不正确");
        };
    }

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthencationTokenFilter(){
        return new JwtAuthenticationTokenFilter();
    }

}
